import React from "react";
import { Form, Input, Button, message } from "antd";
import Link from "next/link";
import styles from "../components/pageComponent/login/login.module.less";
import { connect } from "react-redux";
import { loginByUsername } from "../actions/loginActions";
import { useRouter } from "next/router";
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
type Props = {
  dispatch: any;
};

const Login: React.FC<Props> = ({ dispatch }) => {
  const router = useRouter();
  const onFinish = (values: any) => {
    console.log("Success:", values);
    // TODO 登录逻辑
    dispatch(
      loginByUsername({
        uid: 1,
        username: "zhaojunzhe",
        isAdmin: true,
        avatarUrl:
          "https://bbs.fanruan.com/uc_server/avatar.php?uid=230080&size=small",
      })
    );
    const urlSearch = new URLSearchParams(window.location.search);
    const redirect = urlSearch.get("redirect");
    if (redirect) {
      router.push(redirect);
    } else {
      message.success("登录成功", 1, () => {
        router.push({
          pathname: "/",
        });
      });
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div className={styles.loginWrapper}>
      <div className={styles.loginWrapper_inner}>
        <h1 className={styles.title}>登录</h1>
        <Form
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button
              type="primary"
              htmlType="submit"
              className={styles.login_btn}
            >
              登录
            </Button>
            <p>
              尚无账号,点此<Link href={"/register"}>注册</Link>
            </p>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default connect()(Login);
